package org.bbx.autoops.controller;


import cn.hutool.core.date.DateUtil;
import com.huaweicloud.sdk.core.utils.StringUtils;
import com.huaweicloud.sdk.hss.v5.model.Host;
import com.huaweicloud.sdk.rms.v1.model.ResourceEntity;
import lombok.extern.slf4j.Slf4j;
import org.bbx.autoops.builder.TemplateBuilder;
import org.bbx.autoops.entity.MetricEntity;
import org.bbx.autoops.entity.MetricNameEntity;
import org.bbx.autoops.enums.NamespaceEnum;
import org.bbx.autoops.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static org.bbx.autoops.utils.ProcessContent.process;
import static org.bbx.autoops.utils.RandomStringGenerator.generateRandomString;


@Slf4j
@RestController
@RequestMapping("doc")
public class DocController {

    @Autowired
    private TemplateBuilder templateBuilder;

    @Autowired
    private CesUtil cesUtil;

    @Autowired
    private CostAnalysedUtil costAnalysedUtil;


    @Autowired
    private MetricEntity metricEntity;

    @Autowired
    private MetricNameEntity metricNameEntity;

    @Autowired
    private HssUtil hssUtil;

    @Autowired
    private ListAllResourcesUtil listAllResourcesUtil;
    @Autowired
    private StringHttpMessageConverter stringHttpMessageConverter;


    @RequestMapping("/get")
    public String get(Long from, Long to) throws IOException, IllegalAccessException {

            Map<String, ResourceEntity> resourcesMap = listAllResourcesUtil.getResourcesMap();


        //全局 titleLevel1No
        AtomicInteger titleLevel1No = new AtomicInteger(1);
        AtomicInteger titleLevel2No = new AtomicInteger(1);

        StringBuilder baseBuilder = new StringBuilder();
        // 图标数据
        StringBuilder chartConfigBuilder = new StringBuilder();
        // 标题
        StringBuilder titleLevel1Builder = new StringBuilder();
        StringBuilder titleLevel2Builder = new StringBuilder();
        StringBuilder titleLevel3Builder = new StringBuilder();
        StringBuilder titleLevel4Builder = new StringBuilder();

        StringBuilder resTrBuilder = new StringBuilder();
        StringBuilder resTableBuilder = new StringBuilder();

        StringBuilder hssTrBuilder = new StringBuilder();
        StringBuilder hssTableBuilder = new StringBuilder();

        //监控instance    key: 实例类型  例如 ecs，rds    value ：对应类型服务命名空间
        Map<String, NamespaceEnum> namespaceEnumMap = Arrays.stream(NamespaceEnum.values()).collect(Collectors.toMap(NamespaceEnum::getAlias, i -> i));
        //监控instance    key: 实例类型  例如 ecs，rds    value ：对应类型实例ID
        Map<String, List<String>> metricEntityMap = EntityToMapUtils.getMap(metricEntity);
        //监控指标    key: 实例类型  例如 ecs，rds    value ：对应类型实例的监控指标
        Map<String, List<String>> metricNameEntityMap = EntityToMapUtils.getMap(metricNameEntity);


        String id = generateRandomString(8);
        process(titleLevel1Builder, templateBuilder.level1TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "、巡检目的", templateBuilder.targetTemplate.toString()));
        titleLevel1No.getAndIncrement();


        id = generateRandomString(8);
        process(titleLevel1Builder, templateBuilder.level1TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "、巡检内容", templateBuilder.checkContentTemplate.toString()));
        titleLevel1No.getAndIncrement();


        AtomicInteger resultNo = new AtomicInteger(1);


        for (String i : metricEntityMap.keySet()) {
            List<String> intanceIdList = metricEntityMap.get(i);
            if (!intanceIdList.isEmpty()) {
                NamespaceEnum namespaceEnum = namespaceEnumMap.get(i);

                AtomicInteger titleLevel3No = new AtomicInteger(1);
                for (String j : intanceIdList) {
                    String name = j;
                    ResourceEntity resourceEntity = resourcesMap.get(j);
                    if (resourceEntity != null) {
                        name = resourceEntity.getName();
                    }
                    AtomicInteger titleLevel4No = new AtomicInteger(1);
                    for (String ec : metricNameEntityMap.get(i)) {
                        String[] s = ec.split(":");
                        ec = s[0];
                        String threshold = "-";
                        String status = "-";


                        //标题
                        id = generateRandomString(8);
                        process(titleLevel4Builder, templateBuilder.level4TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "." + titleLevel2No + "." + titleLevel3No + "." + titleLevel4No + "、" + ec, ""));
                        titleLevel4No.getAndIncrement();

                        // 图表
                        log.info("metricName[{}]", ec);
                        Map<String, String> map = cesUtil.getXYChartDataMap(id, namespaceEnum.getNamespace(), ec, namespaceEnum.getDim() + "," + j, from, to);
                        process(chartConfigBuilder, templateBuilder.xyChartTemplate, map);


                        //结果
                        String maxValue = map.get("maxValue");
                        if (s.length > 1) {
                            threshold = s[1];
                            status = new BigDecimal(maxValue).compareTo(new BigDecimal(threshold)) > 0 ? "异常" : "正常";
                        }
                        process(resTrBuilder, templateBuilder.resTrTemplate, ParamPackage.tr(resultNo.toString(), i,name , j, ec, threshold, status));
                        resultNo.getAndIncrement();

                    }


                    // 处理三级标题
                    id = generateRandomString(8);
                    process(titleLevel3Builder, templateBuilder.level3TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "." + titleLevel2No + "." + titleLevel3No + "、" + name, titleLevel4Builder.toString()));
                    titleLevel3No.getAndIncrement();
                    titleLevel4Builder.setLength(0);

                }
                // 处理二级标题
                id = generateRandomString(8);
                process(titleLevel2Builder, templateBuilder.level2TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "." + titleLevel2No + "、" + namespaceEnum.getAlias(), titleLevel3Builder.toString()));
                titleLevel2No.getAndIncrement();
                titleLevel3Builder.setLength(0);

            }
        }
        //成本分析 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //标题
        id = generateRandomString(8);
        process(titleLevel2Builder, templateBuilder.level2TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "." + titleLevel2No + "、成本分析", templateBuilder.chartContainerTemplate.toString()));
        titleLevel2No.getAndIncrement();

        // 图表
        Map<String, String> map = costAnalysedUtil.getXYChartDataMap(id, DateUtil.date(from).toDateStr(), DateUtil.date(to).toDateStr());
        process(chartConfigBuilder, templateBuilder.xyChartTemplate, map);

        //结果
        process(resTrBuilder, templateBuilder.resTrTemplate, ParamPackage.tr(resultNo.toString(), "成本", "-","-", "-", "-", "-"));
        resultNo.getAndIncrement();


        // hss ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        // 处理表格
        List<Host> hostList = hssUtil.listHostStatus();
        hostList.forEach(i -> process(hssTrBuilder, templateBuilder.hssTrTemplate, ParamPackage.getHssTabletDataMap(i)));
        process(hssTableBuilder, templateBuilder.hssTableTemplate, ParamPackage.table(hssTrBuilder.toString()));
        //标题
        id = generateRandomString(8);
        process(titleLevel2Builder, templateBuilder.level2TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "." + titleLevel2No + "、hss", hssTableBuilder.toString()));
        titleLevel2No.getAndIncrement();

        // 结果
        process(resTrBuilder, templateBuilder.resTrTemplate, ParamPackage.tr(resultNo.toString(), "hss", "-","-", "-", "-", "-"));
        resultNo.getAndIncrement();


        // 处理一级标题
        id = generateRandomString(8);
        process(titleLevel1Builder, templateBuilder.level1TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "、巡检过程", titleLevel2Builder.toString()));
        titleLevel1No.getAndIncrement();
        titleLevel2Builder.setLength(0);
        titleLevel2No.set(1);

        // 处理表格
        process(resTableBuilder, templateBuilder.resTableTemplate, ParamPackage.table(resTrBuilder.toString()));

        id = generateRandomString(8);
        process(titleLevel1Builder, templateBuilder.level1TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "、巡检结果", resTableBuilder.toString()));
        titleLevel1No.getAndIncrement();


        // 处理一级标题
        id = generateRandomString(8);
        process(titleLevel1Builder, templateBuilder.level1TitleTemplate, ParamPackage.titleLevel(id, titleLevel1No + "、存在问题点", templateBuilder.contentTextTemplate.toString()));
        titleLevel1No.getAndIncrement();
        titleLevel2Builder.setLength(0);
        titleLevel2No.set(1);


        // 处理 base
        process(baseBuilder, templateBuilder.baseHtml, ParamPackage.base(titleLevel1Builder.toString(), chartConfigBuilder.toString()));
        MdFileUtil.wiriteMDFile(baseBuilder.toString(), "aaaaa.html");

        return "";
    }


}
